package com.fyzk.activity.user;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.App;
import com.fyzk.activity.app.AppToast;
import com.fyzk.activity.main.MainGroupActivityI;
import com.fyzk.base.BaseActivity;
import com.fyzk.bean.LoginResponse;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.interfaces.onTopTitleClickListener;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LogUtil;
import com.fyzk.utils.LogUtils;
import com.fyzk.utils.SoftKeyboardUtils;
import com.fyzk.view.TopTitleView;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import http.Common.CommandUtil;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

import static com.fyzk.activity.user.RegisteActivity.center_chongFa;
import static com.fyzk.activity.user.RegisteActivity.daojs_yzm;

@ContentView(R.layout.login)
public class LoginActivity extends BaseActivity implements onTopTitleClickListener {

    private TopTitleView topView;
    //     中部 center 登录按钮
    private TextView center_login;
    //     中部 center 密码输入框
    private EditText center_pwd;
    //     中部 center 用户名输入框 AutoCompleteTextview
    private AutoCompleteTextView center_user;
    //    底部 bottom 注册链接、忘记密码链接
    private TextView bottom_wangJiPow;
    private TextView bottom_zhuCe;

    //     输入框提示信息 数据
    private List<String> users = new ArrayList<String>();

    @ViewInject(R.id.login_radioGroup)
    private RadioGroup login_radioGroup;
    @ViewInject(R.id.login_center_ll)
    private LinearLayout login_center_ll;
    @ViewInject(R.id.login_ll_verifycode)
    private LinearLayout login_ll_verifycode;
    @ViewInject(R.id.login_verifycode)
    private TextView login_verifycode;
    @ViewInject(R.id.phonenum)
    private EditText phonenum;
    @ViewInject(R.id.verifycode)
    private EditText verifycode;
    @ViewInject(R.id.login_getVerifycode)
    private TextView login_getVerifycode;
    @ViewInject(R.id.iv_del)
    private ImageView ivDel;
    private boolean isClickVerifyCodeBtn = false;

    private Handler handler_yzm;

    private static final int DAOJISHI = 60;
    private Runnable runnable_yzm;

    private final int LOGINTYPE_USERPSW = 0;
    private final int LOGINTYPE_VERIFYCODE = 1;
    private int loginType = LOGINTYPE_USERPSW;

    boolean hasSended = false;

    // 微信登录
    @ViewInject(R.id.login_weixin)
    private ImageView weiXinLogin_iv;

    public static LoginActivity _instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (_instance == null) {
            _instance = this;
        }
        users = getUsers();
        info();
        login_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.tab_userpassword:
                        loginType = LOGINTYPE_USERPSW;
                        login_center_ll.setVisibility(View.VISIBLE);
                        login_ll_verifycode.setVisibility(View.GONE);
                        break;
                    case R.id.tab_verifycode:
                        loginType = LOGINTYPE_VERIFYCODE;
                        login_center_ll.setVisibility(View.GONE);
                        login_ll_verifycode.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });

        handler_yzm = new Handler();
        runnable_yzm = new Runnable() {

            @Override
            public void run() {
                djs_yzm();
            }
        };
    }

    @Override
    public void finish() {
        if (null != phonenum) {
            SoftKeyboardUtils.hintSoftKeyboard(this.getApplicationContext(), phonenum);
        }
        if (null != handler_yzm) {
            handler_yzm.removeCallbacksAndMessages(null);
        }
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.finish();
    }

    /**
     * 验证码 有效倒计时
     */
    private void djs_yzm() {
        handler_yzm.postDelayed(runnable_yzm, 1000);
        if (daojs_yzm == 0 || daojs_yzm == DAOJISHI) {
            handler_yzm.removeCallbacks(runnable_yzm);
            if (loginType == LOGINTYPE_USERPSW) {
                center_chongFa.setClickable(true);
                center_chongFa.setTextColor(Color.parseColor("#1a1a1a"));
                if (!hasSended) {
                    center_chongFa.setText(R.string.zhuce_center_fa);
                } else {
                    center_chongFa.setText(R.string.zhuce_center_chongfa);
                }
            } else {
                login_getVerifycode.setClickable(true);
                login_getVerifycode.setTextColor(Color.parseColor("#1a1a1a"));
                if (!hasSended) {
                    login_getVerifycode.setText(R.string.zhuce_center_fa);
                } else {
                    login_getVerifycode.setText(R.string.zhuce_center_chongfa);
                }
            }
            daojs_yzm = DAOJISHI;
        } else {
            hasSended = true;
            if (loginType == LOGINTYPE_USERPSW) {
                center_chongFa.setTextColor(Color.GRAY);
                center_chongFa.setClickable(false);
                center_chongFa.setText(daojs_yzm + "秒后可重发");
            } else {
                login_getVerifycode.setTextColor(Color.GRAY);
                login_getVerifycode.setClickable(false);
                login_getVerifycode.setText(daojs_yzm + "秒后可重发");
            }
            daojs_yzm -= 1;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (MySharedPreferences.getInstance().getLoginStatus()) {
            Intent intent = new Intent(LoginActivity.this, MainGroupActivityI.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        cancelProgressDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SoftKeyboardUtils.fixInputMethodManagerLeak(this);
        _instance = null;
    }

    /**
     * 初始化控件
     */
    private void info() {
        //根据路径得到Typeface
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/pingfang.ttf");

        topView = (TopTitleView) findViewById(R.id.top_redpacketlist);
        topView.setOnTitleClickListener(this);
        topView.setRightImg(R.drawable.dj_register1);
        topView.setCenterText("登录");
        // 中部 center
        center_login = (TextView) findViewById(R.id.login_userpassword);
        center_login.setTypeface(tf);
        center_user = (AutoCompleteTextView) findViewById(R.id.login_et_user);
        center_user.setTypeface(tf);
        center_pwd = (EditText) findViewById(R.id.login_et_pwd);
        center_pwd.setTypeface(tf);
        // 底部 bottom
        bottom_zhuCe = (TextView) findViewById(R.id.login_bottom_zhuce);
        bottom_wangJiPow = (TextView) findViewById(R.id.login_bottom_wangjimima);
        bottom_zhuCe.setTypeface(tf);
        bottom_wangJiPow.setTypeface(tf);
        // 中部
        center_login.setOnClickListener(new LoginOnClick());
        login_getVerifycode.setOnClickListener(new LoginOnClick());
        login_verifycode.setOnClickListener(new LoginOnClick());
        weiXinLogin_iv.setOnClickListener(new LoginOnClick());
        ivDel.setOnClickListener(new LoginOnClick());
        // Auto 适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                R.layout.auto_down_style, R.id.auto_down_style_tv, users);
        center_user.setAdapter(adapter);
        if (users != null && users.size() != 0) {

            center_user.setText(users.get(0) + "");
            ivDel.setVisibility(View.VISIBLE);
            for (int i = 0; i < users.size(); i++) {
                Log.e("", "第" + i + ":" + users.get(i));
            }
        }

        // 底部
        bottom_zhuCe.setOnClickListener(new LoginOnClick());
        bottom_wangJiPow.setOnClickListener(new LoginOnClick());

        center_user.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String trim = editable.toString().trim();
                if (trim.length() > 0) {
                    ivDel.setVisibility(View.VISIBLE);
                } else {
                    ivDel.setVisibility(View.GONE);
                }
            }
        });
    }

    /**
     * 读取首选项中 用户名
     */
    private List<String> getUsers() {
        String userStrings[];
        String userString = MySharedPreferences.getInstance().getUserNames();
        if (!userString.equals("")) {

            userStrings = userString.split(",");
            for (int i = 0; i < userStrings.length; i++) {
                users.add(userStrings[i].toString());
            }
        } else {
            userStrings = null;
        }

        return users;
    }

    /**
     * 写入首选项
     */
    private void writeShared() {
        String writeString = "";
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).equals(center_user.getText().toString())) {
                users.remove(i);
                i--;
            }
        }
        users.add(0, center_user.getText().toString());

        for (int i = 0; i < users.size(); i++) {
            writeString += "," + users.get(i);
        }
        writeString = writeString.substring(1, writeString.length());

        MySharedPreferences.getInstance().setUserNames(writeString);
    }


    /**
     * 非空验证
     */
    private boolean isNull(EditText editText) {
        if (editText.getText() == null
                || editText.getText().toString().equals("")) {
            editText.requestFocus();
            return true;
        }

        return false;
    }

    /**
     * 登录确认
     *
     * @return
     */
    private boolean loginYanZheng() {

        if (isNull(center_user)) {
            AppToast.getToast().show("用户名不能为空！");
            return false;
        }
        if (isNull(center_pwd)) {
            AppToast.getToast().show("密码不能为空！");
            return false;
        }

        return true;
    }

    /**
     * 登录确认
     *
     * @return
     */
    private boolean loginYanZhengVerify() {
        String phoneNum = "";
        phoneNum = phonenum.getText().toString();
        if (phoneNum.length() != 11) {
            AppToast.getToast().show("手机号格式不正确！");
            return false;
        }
        if (isNull(verifycode)) {
            AppToast.getToast().show("验证码不能为空！");
            return false;
        }
        return true;
    }

    /**
     *  * 登录
     */
    private void requestLogin() {
        String username = center_user.getText().toString();
        String password = center_pwd.getText().toString();
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("username", username);
            request_json.put("password", password);
            httpPostJson(CommandUtil.USER_LOGIN, Commands.LOGIN, request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     *  验证码登录
     */
    private void requestVerifyLogin() {
        String username = phonenum.getText().toString();
        String password = verifycode.getText().toString();
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("mobilephone", username);
            request_json.put("authcode", password);
            httpPostJson(CommandUtil.PHONEAUTHCODELOGIN, Commands.PHONEAUTHCODELOGIN,
                    request_json, true);
        } catch (JSONException e) {

        }
    }

    /**
     *  获取登录验证码
     */
    private void requestVerifyCode() {
        String username = phonenum.getText().toString();
        try {
            JSONObject request_json = new JSONObject();
            request_json.put("mobilephone", username);
            httpPostJson(CommandUtil.GETPHONEAUTHCODE, Commands.GETPHONEAUTHCODE, request_json,
                    true);
        } catch (JSONException e) {

        }
    }

    LoginResponse loginResponse;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.USER_LOGIN:
            case CommandUtil.PHONEAUTHCODELOGIN:
                AppToast.getToast().show("登录成功");
                loginResponse = JSON.parseObject(resultBean.getData(), LoginResponse.class);
                writeShared();
                MySharedPreferences.getInstance().setLoginStatus(true);
                MySharedPreferences.getInstance().setUserNo(loginResponse.getUserno());
                MySharedPreferences.getInstance().setUserName(loginResponse.getUsername());
                MySharedPreferences.getInstance().setAlias(loginResponse.getAlias());
                MySharedPreferences.getInstance().setAuthToken(loginResponse.getAccessToken());
                MySharedPreferences.getInstance().setBalance(PublicMethod.formatBalance
                        (Double.parseDouble(loginResponse.getBalance())));
                MySharedPreferences.getInstance().setDrawbalance(PublicMethod.formatBalance
                        (Double.parseDouble(loginResponse.getDrawbalance())));
                MySharedPreferences.getInstance().setPhotoUrl(loginResponse.getPhotoUrl());
                mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, loginResponse.getUserno()));

                Intent intent = new Intent(LoginActivity.this, MainGroupActivityI.class);
                startActivity(intent);
                finish();

                break;
            case CommandUtil.GETPHONEAUTHCODE:
                AppToast.getToast().show(resultBean.getMsg());
                daojs_yzm = DAOJISHI - 1;
                if (loginType == LOGINTYPE_USERPSW) {
                    center_chongFa.setClickable(false);
                    center_chongFa.setTextColor(Color.GRAY);
                    center_chongFa.setText(daojs_yzm + "秒\n后重发");
                } else {
                    login_getVerifycode.setClickable(false);
                    login_getVerifycode.setTextColor(Color.GRAY);
                    login_getVerifycode.setText(daojs_yzm + "秒\n后重发");

                }
                handler_yzm.post(runnable_yzm);
                break;
            default:
                break;
        }
    }


    @Override
    protected void parserMessage(Message msg) {
        super.parserMessage(msg);
        switch (msg.what) {
            case MSG_SET_ALIAS:
                LogUtil.v("Set alias in handler.");
                JPushInterface.setAlias(getApplicationContext(), 0, (String) msg.obj);
                break;
        }
    }

    private static final int MSG_SET_ALIAS = 1001;

    protected void onFailure(int requestCode, String errorCode, String message) {

        LogUtils.e("====errorCode====" + errorCode);
        LogUtils.e("====message====" + message);

        switch (requestCode) {
            case CommandUtil.PHONEAUTHCODELOGIN:
            case CommandUtil.USER_LOGIN:
                if (TextUtil.isEmpty(message)) {
                    showToast("网络异常");
                } else {
                    showToast(message);
                }
                break;
            case CommandUtil.GETPHONEAUTHCODE:
                if (errorCode.equals("40002")) {
                    AlertDialog dialog = new AlertDialog.Builder(this).setTitle("提示").setMessage
                            ("手机号码未注册").setPositiveButton("去注册", new DialogInterface
                            .OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(LoginActivity.this, RegisteActivity.class);
                            intent.putExtra("phone", phonenum.getText().toString());
                            startActivity(intent);
                        }
                    }).setNegativeButton("返回", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).create();
                    dialog.show();
                } else {
                    if (TextUtil.isEmpty(message)) {
                        showToast("网络异常");
                    } else {
                        showToast(message);
                    }
                }
                break;
        }
    }

    /**
     * 单击事件
     *
     * @author Administrator
     */
    class LoginOnClick implements OnClickListener {

        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.login_userpassword: // 登录
                    if (loginYanZheng()) {
                        requestLogin();
                    }
                    break;

                case R.id.login_verifycode: // 登录
                    if (loginYanZhengVerify()) {
                        requestVerifyLogin();
                    }
                    break;
                case R.id.login_bottom_zhuce:// 注册
                    tendToRegister();
                    break;
                case R.id.login_bottom_wangjimima:
                    new AlertDialog.Builder(LoginActivity.this).setTitle("提示").setMessage
                            ("直接用手机号验证码登录，无须密码哦").setNegativeButton("去找回密码", new DialogInterface
                            .OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            Intent intent = new Intent(LoginActivity.this,
                                    ForgotPwdActivity.class);
                            startActivity(intent);
                        }
                    }).setPositiveButton("手机号验证码登录", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                    login_radioGroup.check(R.id.tab_verifycode);
                                }
                            }
                    ).create().show();

                    break;
                case R.id.login_getVerifycode:
                    if (phonenum.getText().length() == 11) {
                        isClickVerifyCodeBtn = true;
                        requestVerifyCode();
                    } else {
                        showToast("请输入正确的手机格式");
                    }
                    break;
                case R.id.login_weixin:
                    if (!((App) LoginActivity.this.getApplication()).getWXApi().isWXAppInstalled
                            ()) {
                        //提醒用户没有按照微信
                        AppToast.getToast().show("没有安装微信,请先安装微信!");
                        return;
                    }
                    showProgressDialog();
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "WXLogin";
                    ((App) LoginActivity.this.getApplication()).getWXApi().sendReq(req);
                    break;
                case R.id.iv_del:
                    center_user.setText("");
                    break;
                default:
                    break;
            }
        }

    }

    private void tendToRegister() {
        Intent intent = new Intent(LoginActivity.this, RegisteActivity.class);
        startActivity(intent);
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onCenterClick() {
    }

    @Override
    public void onRightClick() {
        tendToRegister();
    }

    @Override
    public void onRight2Click() {
    }

}
